package y2018.eclipseuserlib;

import com.lu.jdog.util.TextUtil;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class Node {
    private boolean isShort;
    private String name;
    private Map<String, String> attrMap;
    private List<Node> childList;

    public Node() {
        if (childList == null) {
            childList = new ArrayList<>();
        }
        if (attrMap == null) {
            attrMap = new Hashtable<>();
        }
    }

    public Node(String name) {
        this();
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Map<String, String> getAttrs() {
        return attrMap;
    }

    public void setAttrs(Map<String, String> attrs) {
        this.attrMap = attrs;
    }

    public List<Node> getChildList() {
        return childList;
    }

    public void setChildList(List<Node> childList) {
        this.childList = childList;
    }

    public void addChild(Node node) {
        childList.add(node);
    }

    public void addAttr(String name, String value) {
        attrMap.put(name, value);
    }

    public boolean isShort() {
        return isShort;
    }

    public void setShort(boolean isShort) {
        this.isShort = isShort;
    }


    public String getInnerXml() {
        if (TextUtil.isEmpty(this.name)) {
            return "";
        }

        String xml = "<" + this.name;

        for (Entry<String, String> attr : this.attrMap.entrySet()) {
            String k = attr.getKey();
            String v = attr.getValue();

            if (!TextUtil.isEmpty(k)) {
                if (v == null) {
                    xml += " " + k + "\"";
                } else {
                    xml += " " + k + "=\"" + v + "\"";
                }
            }
        }
        if (this.isShort && this.childList.size() == 0) {
            xml += "/>";
        } else {
            xml += ">";
            for (int i = 0; i < this.childList.size(); i++) {
                xml += this.childList.get(i).getInnerXml();
            }
            xml += "</" + name + ">";
        }

        return xml;
    }

}
